const Controller = require('egg').Controller
/**
 * @Controller 留言
 */
class messageController extends Controller {

  /**
   * @summary 添加留言
 */
  async insert() {
    const { ctx, service } = this
    const body = ctx.request.body
    await service.messageService.insert(body)
    ctx.body = {
      code: 200,
      message: '添加成功'
    }
  }

  /**
   * @summary 删除留言
   * @router post /message/delete
   ** @request query string *id 标识
   * @response 200 testResponse
   * @apikey
 */
  async delete() {
    const { ctx } = this
    const body = ctx.request.body
    const Message = ctx.model.Message
    ctx.validate({
      id: 'string'
    },body)

    const _data = await Message.findById(body.id)
    if(!_data) {
      ctx.throw(422,'_id不正确！')
    }
    _data.remove()
   
    ctx.body = {
      code: 200,
      message: '删除成功'
    }
  }

  /**
   * @summary 修改留言
   * @router post /message/update
   ** @request body updateTitleRequest
   * @response 200 testResponse
   * @apikey
 */
   async update() {
    const { ctx } = this
    const body = ctx.request.body
    const Message = this.ctx.model.Message
    ctx.validate({
      id: 'string',
      content: 'string',
    },body)
    //查找留言
    const _data = await Message.findByIdAndUpdate(body.id,Object.assign(body,{updatedAt: Date.now()})) 
    if(!_data) {
      ctx.throw(422,'_id不正确！')
    }
    ctx.body = {
      code: 200,
      message: _data
    }
  }

  /**
  * @summary 获取留言列表
 */
  async list() {
    const { ctx,service } = this
    const body = ctx.request.query
    ctx.validate({
      pageNum: 'string'
    },body)
    const data = await service.messageService.list(body)
    ctx.body = {
      code: 200,
      data
    }
  }

  // 回复留言
  async reply() {
    const { ctx } = this
    const body = ctx.request.body
    const messageModel = ctx.model.Message
    ctx.validate({
      id: 'string',
      replyContent: 'string'
    },body)
    body.replyUser = ctx.user._id
    body.updatedAt = Date.now()
    body.status = true
    const data = await messageModel.findByIdAndUpdate({_id: body.id},body)
    ctx.body = {
      code: 200,
      message: '回复成功！',
      data
    }
  }
}

module.exports = messageController